<?php
namespace app\model;

use app\common\model\_Base;

class Article extends _Base
{
    /**
     * 设置关联模型Role
     */
    public function type()
    {
        return $this->hasOne('ArticleType','id','type_id');
    }

    /**
     * 保存数据
     * @param  array $data 数据
     * @return bool       
     */
    public static function doSave($data,$id = '')
    {   
        
        $article = $id?Article::get($id):new Article;
        !empty($data['title']) && $article->title = $data['title'];
        !empty($data['content']) && $article->content = $data['content'];
        !empty($data['type_id']) && $article->type_id = $data['type_id'];
        !empty($data['user_id']) && $article->user_id = $data['user_id'];
        !empty($data['user_type']) && $article->user_type = $data['user_type'];
        !empty($data['user_name']) && $article->user_name = $data['user_name'];

        isset($data['cover']) && $article->cover = $data['cover'];

        isset($data['status']) && strlen($data['status']) > 0 && $article->status = $data['status'];
        isset($data['hot_level']) && strlen($data['hot_level'])>0 && $article->hot_level = $data['hot_level'];
        isset($data['comment_status']) && strlen($data['comment_status'])>0 && $article->comment_status = $data['comment_status'];
        
        $article->save();
        return false;
    }

    /**
     * 删除数据 软删除 二次真实删除
     * @param  integer $id 数据编号
     * @return bool       
     */
    public static function doDelete($id)
    {
        $config = Article::destroy($id);
        return false;
    }

    /**
     * 获取数据
     * @param  array    $cond  条件
     * @param  string   $alias 条件表别名
     * @param  integer  $page  页码
     * @param  integer  $size 每页条数
     * @return array
     */
    public static function doList($cond = [], $page = 1, $size = 10, $order = 'id desc')
    {   
        $total = Article::where($cond)->count();
        $list = Article::with('type')->where($cond)->page($page,$size)->order($order)->select();
        if(!$list->isEmpty()){
            foreach ($list as $key => &$value) {
                $type_name = $value['type']['name'];
                unset($value['type']);
                $value['type'] = $type_name;
                $value->user_type = $value->user_type == Log::TYPE_ADMIN ? '管理员' : '会员';
            }
        }
        return ['total' => $total,'list' => $list];
    }
}